package cn.kgc.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author mosin
 * date 2022/2/10
 * @version 1.0
 * java 操作数据库的工具类
 */
public final class JDBCUtil {

   static Connection connection = null;
   private JDBCUtil(){}


    static{
        //获取配置文件参数
        InputStream ins = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties ps = new Properties();
        try {
            ps.load(ins);
            //driver
            String  driver = ps.getProperty("jdbc.driver");
            String  username = ps.getProperty("jdbc.username");
            String  password = ps.getProperty("jdbc.password");
            String  url = ps.getProperty("jdbc.url");
             Class.forName(driver);
             connection =  DriverManager.getConnection(url,username,password);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //获取连接的方法
    public  static Connection getConnection(){
       return  connection;
    }

    //释放资源的方法
    public  static void closeAll(ResultSet rs, Statement stmt,Connection connection){

            try {
                if(rs!=null){  // 避免空指针
                    rs.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            try {
                if(stmt!=null){
                    stmt.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            try {
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

        }

}

